//
//  HomePageViewController.m
//  ZAKER
//
//  Created by dllo on 15/8/21.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "HomePageViewController.h"
#import "HomeTableview.h"
#import "HeaderButton.h"
#import "WangYiModel.h"


@interface HomePageViewController ()<UMSocialUIDelegate, UITableViewDataSource, UITableViewDelegate , UIScrollViewDelegate>
{
    
    NSNumber *firstNum;
    NSNumber *secondNum;
    
}
@property (nonatomic, strong) JCFlipPageView *flipPage;
@property (nonatomic, retain) WangYiModel *model;

@property (nonatomic, retain) HomeModel *detailModel;
@property (nonatomic, retain) NSMutableArray *buttonArray; // 存放顶部按钮的信息
@property (nonatomic, retain) NSMutableArray *talbeViewArray;
@property (nonatomic, retain) UIActivityIndicatorView *activity;

@property (nonatomic, retain) UIScrollView *headerScro; // 顶部滚动Scroll, 热点,头条, 稀奇
@property (nonatomic, retain) NSDictionary *buttonDic; // 点击不同按钮dic
@property (nonatomic, retain) MBProgressHUD *mb;


@property (nonatomic, retain) UITableView *homePageTable;  // 头条tableView
@property (nonatomic, retain) UITableView *shehuiTableView; // 社会tableview
@property (nonatomic, retain) UITableView *redianTableview; // 热点tableView
@property (nonatomic, retain) UIScrollView *homeScrollView;

@end

@implementation HomePageViewController
-(void)dealloc
{
    [_flipPage release];
    [_detailModel release];
    [_buttonArray release];
    [_homePageTable release];
    [_activity release];
    [_headerScro release];
    [_buttonDic release];
    [_mb release];
    [_homeScrollView release];
    [_talbeViewArray release];
    
    [_shehuiTableView release];
    [_redianTableview release];
    
    [super dealloc];
    
}

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.buttonArray = [NSMutableArray array];
        
        self.talbeViewArray = [NSMutableArray arrayWithObjects:[NSMutableArray array], [NSMutableArray array], [NSMutableArray array],[NSMutableArray array],[NSMutableArray array],[NSMutableArray array], nil];
        
        NSString *path = [[NSBundle mainBundle] pathForResource:@"HomePage" ofType:@"json"];
        NSData *data = [NSData dataWithContentsOfFile:path];
        
        [self.buttonArray addObjectsFromArray:[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]];
        
    }
    
    return self;
    
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor  = RGBACOLOR(135, 206, 255, 1);
    
    self.navigationItem.title = @"新闻";
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 创建scrollView
    [self creatScrollView];
    
    // 创建顶部横向按钮
    [self createHeaderButton];
  
    [self creathandleData];
    
 
    
}
- (void)creathandleData
{
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    _mb = [[MBProgressHUD alloc] initWithView:window];
    [self.view addSubview:_mb];
    _mb.labelText = @"正在加载";
    [_mb show:YES];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        if (_mb != nil) {
            [_mb removeFromSuperview];
            
            UIAlertController *a = [UIAlertController alertControllerWithTitle:@"提示" message:@"数据加载失败" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
            }];
            [a addAction:sure];
            
            // 模态推出
            [self presentViewController:a animated:YES completion:^{
                
            }];
        }
    });
}

#pragma mark - 创建头条, 热点, 稀奇的三个button, 放在scrollView上

- (void)createHeaderButton
{
    self.headerScro = [[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, HeaderScrollHeight)] autorelease];
    _headerScro.backgroundColor = [UIColor colorWithRed:244 / 255.0 green:244 / 255.0 blue:244 / 255.0 alpha:1.0f];
    _headerScro.bounces = NO;
    [self.view addSubview:_headerScro];

    // 创建不同按钮
       for (int i = 0; i < [self.buttonArray count]; i++) {
        
        HeaderButton *button = [[HeaderButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width/self.buttonArray.count *i , 5, self.view.frame.size.width/self.buttonArray.count, 30 * myHeight)];
        
        NSDictionary *dic = [self.buttonArray objectAtIndex:i];
        NSString *name = dic[@"name"];
        button.num = i;
        [button setTitle:name forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_headerScro addSubview:button];
       
        
        // 默认调用第一个按钮
        if (button.num == 0) {
            
            [self buttonAction:button];
            
        }
    }
    
    _headerScro.contentSize = CGSizeMake(self.view.frame.size.width, 0);
    
}


#warning 没走
#pragma mark - 加风火轮
- (UIActivityIndicatorView *)activity
{
    if (_activity == nil) {
        
        self.activity = [[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
    }
    return _activity;
    
    
}


- (void)getConnectionWithURL:(NSString *)url dicNum:(NSString *)num tableView:(HomeTableview *)tablleview
{
    url = [NSString stringWithFormat:@"%@%@-%@.html", url, firstNum, secondNum];
    [MyAFNetworking GetWithURL:url dic:nil data:^(id responsder) {
        NSArray *array = responsder[num];
        for (NSDictionary *dic in array) {
            WangYiModel *model = [[WangYiModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            model.editor = dic[@"editor"];
            
            // 以下条件过滤掉
            if (![model.imgextra count] != 0 || [model.editor count] != 0) {
                [[self.talbeViewArray objectAtIndex:tablleview.num] addObject:model];
                [model release];
            }
        }
        [tablleview reloadData];
        [tablleview headerEndRefreshing];
        [tablleview footerEndRefreshing];
        [_mb hide:YES];
        _mb = nil;
    }];
}



#pragma mark - 创建TableView以及他的协议方法, 第一页的tableView, 算上面的照片
- (void)createTableView
{
    
    for (int i = 0; i < self.buttonArray.count; i++) {
        
        HomeTableview *tableview = [[[HomeTableview alloc] initWithFrame:CGRectMake(self.view.frame.size.width * i, 0, self.view.frame.size.width, self.view.frame.size.height - 49 - 64 - HeaderScrollHeight  * myHeight) style:UITableViewStylePlain] autorelease];
        [self.homeScrollView addSubview:tableview];
        
        tableview.num = i;
        
        tableview.delegate = self;
        tableview.dataSource = self;
        
        
        [tableview registerClass:[HeaderViewCell class] forCellReuseIdentifier:@"HeaderViewCell"];
        [tableview registerClass:[CustomCell class] forCellReuseIdentifier:@"CustomCell"];
        
        // 添加上拉刷新控件
        [tableview addFooterWithCallback:^{
            
            firstNum = secondNum;
            secondNum = @(secondNum.integerValue + 21);
            
            self.buttonDic = [self.buttonArray objectAtIndex:tableview.num];
            [self getConnectionWithURL:_buttonDic[@"url"] dicNum:_buttonDic[@"dicNum"] tableView:tableview];
            
        }];
        
        // 添加下拉加载控件
        [tableview addHeaderWithCallback:^{
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [[self.talbeViewArray objectAtIndex:tableview.num] removeAllObjects];
                firstNum = @0;
                secondNum = @20;
                self.buttonDic = [self.buttonArray objectAtIndex:tableview.num];
                [self getConnectionWithURL:_buttonDic[@"url"] dicNum:_buttonDic[@"dicNum"] tableView:tableview];
                
            });
        }];
        
       // 创建后加载数据
        firstNum = @0;
        secondNum = @20;
        self.buttonDic = [self.buttonArray objectAtIndex:tableview.num];
       [self getConnectionWithURL:_buttonDic[@"url"] dicNum:_buttonDic[@"dicNum"] tableView:tableview];

    }
    
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (0 == indexPath.row) {
       
        return 230 * myHeight;
    }
    else {
        
        UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
        
        return cell.frame.size.height;
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    HomeTableview *table = (HomeTableview *)tableView;
    return [[_talbeViewArray objectAtIndex:table.num] count];
}


#pragma mark - 创建滚动视图
- (void)creatScrollView
{
    self.homeScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, HeaderScrollHeight * myHeight, self.view.frame.size.width, self.view.frame.size.height)];
    [self.view addSubview:self.homeScrollView];
    [_homeScrollView release];
    [self createTableView];
    
    self.homeScrollView.contentSize = CGSizeMake(self.view.frame.size.width * self.buttonArray.count, self.view.frame.size.height);
    self.homeScrollView.pagingEnabled = YES;
    self.homeScrollView.delegate = self;
    
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeTableview *table = (HomeTableview *)tableView;
    if ([[_talbeViewArray objectAtIndex:table.num] count] != 0) {
        self.model = [[_talbeViewArray objectAtIndex:table.num] objectAtIndex:indexPath.row];
        
        // 判断数组里的东西去区分用哪种cell
        // 第一种cell就是放顶部大图
        
        if (0 == indexPath.row) {
            
            HeaderViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HeaderViewCell"];
            NSString *imageURL = self.model.imgsrc;
            [cell.headerImage sd_setImageWithURL:[NSURL URLWithString:imageURL]placeholderImage:[UIImage imageNamed:@"HNews.jpg"]];
            [cell.coinImage setImage:[UIImage imageNamed:@"1"]];
            [cell.titleLabel setText:self.model.title];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        else {
            
            CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
            
            [cell.newsImageView sd_setImageWithURL:[NSURL URLWithString:self.model.imgsrc]  placeholderImage:[UIImage imageNamed:@"HNews.jpg"]];
            [cell.newsLabel setText:self.model.digest];
            [cell.newsTitleLabel setText:self.model.title];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    }
    
    return [[UITableViewCell alloc] init];
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeTableview *table = (HomeTableview *)tableView;
    NSInteger ii = table.num;
    WangYiModel *model = [[_talbeViewArray objectAtIndex:ii] objectAtIndex:indexPath.row];
    HomePageWeb *web = [[HomePageWeb alloc] init];
    web.model = model;
    web.url = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/%@/full.html", model.docid];
    web.deoId = model.docid;
    
    [self.navigationController pushViewController:web animated:YES];
    [web release];

}

// 左右滑动改变标题颜色
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (![scrollView isKindOfClass:[HomeTableview class]]) {
        for (HeaderButton *button  in self.headerScro.subviews ) {
            if ([button isKindOfClass:[HeaderButton class]]) {
                if (scrollView.contentOffset.x / self.view.frame.size.width == button.num) {
                    [self buttonAction:button];
                    
                }
            }
        }
        
        
    }
}


#warning 没走
#pragma mark - 创建小圆圈
- (void)createActivityRoll
{
    
    self.activity.frame = CGRectMake(self.flipPage.frame.size.width / 2 - 20 * myWidth, self.flipPage.frame.size.height / 2 - 20 * myHeight, 40 * myWidth, 40 * myHeight);
    self.activity.color = [UIColor grayColor];
    [self.flipPage addSubview:_activity];
    [_activity startAnimating];

}

#pragma mark ** 头条以及热点的照片的点击方法, 点击进入详情

-(void)imageAction:(UIImageView *)myImage
{
    
    HomeDetailViewController *detail = [[HomeDetailViewController alloc]init];
    [detail sendMyImage:myImage.image myModel:_detailModel];
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];
    
}
#pragma mark **button的点击方法

- (void)buttonAction:(id)sender
{
    // 改变按钮的样式
    NSArray *array = self.headerScro.subviews;
    for (UIView *view in array) {
        if ([view isKindOfClass:[HeaderButton class]]) {
            HeaderButton *button = (HeaderButton *)view;
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:17.0f];
        }
    }
    
    HeaderButton *button = (HeaderButton *)sender;
    NSDictionary *dic = [self.buttonArray objectAtIndex:button.num];
    self.buttonDic = dic;
    [button setTitleColor:RGBACOLOR(0, 191, 255, 1) forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:21.0f];
    
    
    [UIView animateWithDuration:0.5 animations:^{
        self.homeScrollView.contentOffset = CGPointMake(self.view.frame.size.width * button.num, 0);
    }];

    
}

#pragma mark ** 分享的点击方法

-(void)shareAction:(id)sender
{
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"55dbb3bfe0f55a5d82006783"
                                      shareText:@"你要分享的文字"
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren, UMShareToDouban, UMShareToTwitter, UMShareToEmail, nil]
                                       delegate:self];
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
   
}

@end
